/**
 * 用于解决浏览器多 Tab 切换账号后，账号信息错乱问题
 */
import React from 'react';
import { Modal } from 'antd';

let lock = false;
let user = null;
let isReFreshing = false;
export default function useCheckLoginStatus() {
    React.useEffect(() => {
        user = JSON.parse(localStorage.getItem('user'));
    }, []);

    // 注意：用于处理通过浏览器多 tab 切换账号，旧页面账号信息错乱问题
    React.useEffect(() => {
        if (lock) {
            return;
        }
        lock = true;

        document.addEventListener('visibilitychange', () => {
            const currentUser = JSON.parse(localStorage.getItem('user'));
            if (!user || !currentUser) {
                return;
            }
            if (user.employeeCode !== currentUser.employeeCode && document.visibilityState === 'visible') {
                if (isReFreshing) {
                    return;
                }
                isReFreshing = true;
                Modal.warning({
                    title: '您已切换账号，将为您刷新页面内容。',
                    okText: '知道了',
                    onOk() {
                        window.location.reload();
                    }
                });
            }
        });
    }, []);
}
